package utils
import(
	"fmt"
	"net"
	"manyuser/common/message"
	"encoding/binary"
	"encoding/json"
)
type Transfer struct{
	Conn net.Conn
	Buf [8096]byte
}
//读取内容
func (this *Transfer)ReadPkg()(mes message.Message, err error){

	fmt.Println("server is reading data len")
	n,err:=this.Conn.Read(this.Buf[:4])
	if n!=4||err!=nil{
		fmt.Println("server reads wrong,",err)
		return 		
	}
	 pkgLen:=binary.BigEndian.Uint32(this.Buf[:4])
	 n,err=this.Conn.Read(this.Buf[:pkgLen])
	 if n!=int(pkgLen)||err!=nil{
		fmt.Println("server is reading data wrong")
		 return 
	 }
	
	 err=json.Unmarshal(this.Buf[:pkgLen],&mes)
	 if err!=nil{
		fmt.Println("json.Unmarshal data wrong")
		return
	 }
	 return
}

//写入内容
func (this *Transfer)WritePkg(data []byte)(err error){
	var pkgLen uint32
	pkgLen=uint32(len(data))

	binary.BigEndian.PutUint32(this.Buf[:4],pkgLen)
	n,err:=this.Conn.Write(this.Buf[:4])
	if n!=4||err!=nil{
		fmt.Println("conn.Write(buf):",err)
		return
	}
	n,err=this.Conn.Write(data)
	if n!=int(pkgLen)||err!=nil{
		fmt.Println("conn.Write(data):",err)
		return
	}
	 return
}